package com.uinnova.product.eam.service.cj.service.impl;

import com.binary.core.lang.StringUtils;
import com.uinnova.product.eam.comm.model.es.EamNotice;
import com.uinnova.product.eam.comm.model.es.EamNoticeKeyword;
import com.uinnova.product.eam.model.cj.domain.ChapterInstance;
import com.uinnova.product.eam.model.cj.domain.PlanChapterCollaborate;
import com.uinnova.product.eam.model.cj.domain.PlanDesignInstance;
import com.uinnova.product.eam.model.cj.domain.PlanDesignShareRecord;
import com.uinnova.product.eam.model.cj.enums.PlanSharePermissionEnum;
import com.uinnova.product.eam.model.cj.vo.CollaborateVO;
import com.uinnova.product.eam.model.cj.vo.PlanChapterCollaborateVO;
import com.uinnova.product.eam.model.cj.vo.SharedUserVO;
import com.uinnova.product.eam.model.constants.NoticeConstant;
import com.uinnova.product.eam.service.IEamNoticeService;
import com.uinnova.product.eam.service.cj.dao.PlanChapterCollaborateDao;
import com.uinnova.product.eam.service.cj.service.PlanChapterCollaborateService;
import com.uinnova.product.eam.service.cj.service.PlanChapterInstanceService;
import com.uinnova.product.eam.service.cj.service.PlanDesignInstanceService;
import com.uinnova.product.eam.service.cj.service.ShareService;
import com.uinnova.product.eam.service.exception.BusinessException;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.business.UserInfo;
import com.uino.dao.util.ESUtil;
import com.uino.service.permission.microservice.IUserSvc;
import com.uino.util.sys.SysUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
public class PlanChapterCollaborateServiceImpl implements PlanChapterCollaborateService {

    @Resource
    private PlanChapterCollaborateDao planChapterCollaborateDao;

    @Resource
    private PlanDesignInstanceService planDesignInstanceService;

    @Resource
    private PlanChapterInstanceService planChapterInstanceService;

    @Resource
    private ShareService shareService;

    @Resource
    private IEamNoticeService eamNoticeService;

    @Resource
    private IUserSvc userSvc;

    @Override
    public void saveOrUpdatePlanChapterCollaborate(PlanChapterCollaborateVO planChapterCollaborateVO) {
        SysUser userInfo = SysUtil.getCurrentUserInfo();
        if (userInfo == null || StringUtils.isEmpty(userInfo.getLoginCode())) {
            throw new BusinessException("登录已过期，请重新登录!");
        }
        PlanDesignInstance planDesignInstance = planDesignInstanceService.getPlanDesignInstance(planChapterCollaborateVO.getPlanId());
        if (planDesignInstance == null) {
            throw new BusinessException("获取方案错误");
        }

        SysUser sysUser = SysUtil.getCurrentUserInfo();
        if (!Objects.equals(sysUser.getLoginCode(), planDesignInstance.getCreatorCode())) {
            List<PlanDesignShareRecord> shareRecordList = shareService.getByPlanId(planDesignInstance.getId());
            if (!CollectionUtils.isEmpty(shareRecordList)) {
                Map<String, Integer> shareRecordMap = shareRecordList.stream().collect(Collectors.toMap(PlanDesignShareRecord::getSharedLoginCode, PlanDesignShareRecord::getPermission));
                if (shareRecordMap == null || shareRecordMap.get(sysUser.getLoginCode()) == null
                        || (!Objects.equals(shareRecordMap.get(sysUser.getLoginCode()), 1)
                        && !Objects.equals(shareRecordMap.get(sysUser.getLoginCode()), 4))) {
                    throw new BusinessException("暂无权限操作方案!");
                }
            } else {
                throw new BusinessException("暂无权限操作方案!");
            }
        }

        // 方案章节协作的用户
        String loginCode = planChapterCollaborateVO.getLoginCode();
        if (StringUtils.isEmpty(loginCode)) {
            throw new BusinessException("请选择要操作的用户!");
        }
        String[] split = loginCode.split(",");
        if (split.length <= 0) {
            throw new BusinessException("请选择要操作的用户!");
        }

        PlanChapterCollaborate planChapterShare = new PlanChapterCollaborate();
        planChapterShare.setPlanId(planChapterCollaborateVO.getPlanId());
        planChapterShare.setChapterId(planChapterCollaborateVO.getChapterId());

        List<PlanChapterCollaborate> listByCdt = planChapterCollaborateDao.getListByCdt(planChapterShare);
        if (!CollectionUtils.isEmpty(listByCdt)) {
            PlanChapterCollaborate planChapterShareInfo = listByCdt.get(0);
            List<String> shareMemberList = planChapterShareInfo.getShareMemberList();
            if (Objects.equals(planChapterCollaborateVO.getStatus(), 0)) {
                if (!CollectionUtils.isEmpty(shareMemberList)) {
                    for (String userLoginCode: split) {
                        if (StringUtils.isEmpty(userLoginCode)) {
                            continue;
                        }
                        shareMemberList.removeIf(next -> Objects.equals(next, userLoginCode));
                    }
                }
            } else {
                if (!CollectionUtils.isEmpty(shareMemberList)) {
                    for (String userLoginCode: split) {
                        if (StringUtils.isEmpty(userLoginCode)) {
                            continue;
                        }
                        if (!shareMemberList.contains(userLoginCode)) {
                            shareMemberList.add(userLoginCode);
                            // 工作台发通知
                            this.pushShareCollaborateNotice(planChapterCollaborateVO.getPlanId(), planChapterCollaborateVO.getChapterId(), userLoginCode);
                        }
                    }
                } else {
                    for (String userLoginCode: split) {
                        if (StringUtils.isEmpty(userLoginCode)) {
                            continue;
                        }
                        shareMemberList = new ArrayList<>();
                        shareMemberList.add(userLoginCode);
                        planChapterShareInfo.setShareMemberList(shareMemberList);
                        // 工作台发通知
                        this.pushShareCollaborateNotice(planChapterCollaborateVO.getPlanId(), planChapterCollaborateVO.getChapterId(), userLoginCode);
                    }
                }
            }
            planChapterShareInfo.setComplete(planChapterCollaborateVO.getComplete());
            planChapterCollaborateDao.saveOrUpdate(planChapterShareInfo);
        } else {
            if (Objects.equals(planChapterCollaborateVO.getStatus(), 1)) {
                List<String> shareMemberList = new ArrayList<>();
                for (String userLoginCode : split) {
                    if (StringUtils.isEmpty(userLoginCode)) {
                        continue;
                    }
                    shareMemberList.add(userLoginCode);
                }
                planChapterShare.setShareMemberList(shareMemberList);
                planChapterShare.setComplete(planChapterCollaborateVO.getComplete());
                planChapterShare.setId(ESUtil.getUUID());
                planChapterShare.setCreatorCode(userInfo.getLoginCode());
                planChapterShare.setCreatorName(userInfo.getUserName());
                planChapterShare.setCreateTime(ESUtil.getNumberDateTime());
                planChapterShare.setModifyTime(ESUtil.getNumberDateTime());
                planChapterShare.setModifierCode(userInfo.getLoginCode());
                planChapterShare.setModifierName(userInfo.getUserName());
                planChapterCollaborateDao.saveOrUpdate(planChapterShare);
                // 工作台发通知
                for (String userLoginCode : split) {
                    if (StringUtils.isEmpty(userLoginCode)) {
                        continue;
                    }
                    this.pushShareCollaborateNotice(planChapterCollaborateVO.getPlanId(), planChapterCollaborateVO.getChapterId(), userLoginCode);
                }
            }
        }
    }

    @Override
    public Boolean completeCollaborate(PlanChapterCollaborateVO planChapterCollaborateVO) {
        PlanDesignInstance planDesignInstance = planDesignInstanceService.getPlanDesignInstance(planChapterCollaborateVO.getPlanId());
        if (planDesignInstance == null) {
            throw new BusinessException("获取方案错误!");
        }
        SysUser sysUser = SysUtil.getCurrentUserInfo();
        if (!Objects.equals(sysUser.getLoginCode(), planDesignInstance.getCreatorCode())) {
            List<PlanDesignShareRecord> shareRecordList = shareService.getByPlanId(planDesignInstance.getId());
            if (!CollectionUtils.isEmpty(shareRecordList)) {
                Map<String, Integer> shareRecordMap = shareRecordList.stream().collect(Collectors.toMap(PlanDesignShareRecord::getSharedLoginCode, PlanDesignShareRecord::getPermission));
                if (shareRecordMap == null || shareRecordMap.get(sysUser.getLoginCode()) == null
                        || (!Objects.equals(shareRecordMap.get(sysUser.getLoginCode()), 1)
                        && !Objects.equals(shareRecordMap.get(sysUser.getLoginCode()), 2)
                        && !Objects.equals(shareRecordMap.get(sysUser.getLoginCode()), 4))) {
                    throw new BusinessException("暂无权限操作方案!");
                }
            } else {
                throw new BusinessException("暂无权限操作方案!");
            }
        }
        PlanChapterCollaborate planChapterShare = new PlanChapterCollaborate();
        planChapterShare.setPlanId(planChapterCollaborateVO.getPlanId());
        planChapterShare.setChapterId(planChapterCollaborateVO.getChapterId());
        List<PlanChapterCollaborate> listByCdt = planChapterCollaborateDao.getListByCdt(planChapterShare);
        if (!CollectionUtils.isEmpty(listByCdt)) {
            PlanChapterCollaborate planChapterCollaborate = listByCdt.get(0);
            if (!Objects.equals(planChapterCollaborateVO.getComplete(), planChapterCollaborate.getComplete())) {
                planChapterCollaborate.setComplete(planChapterCollaborateVO.getComplete());
                planChapterCollaborateDao.saveOrUpdate(planChapterCollaborate);
            }
            if (Objects.equals(planChapterCollaborateVO.getComplete(), 1)) {
                // 工作台发通知
                this.pushCompleteCollaborateNotice(planChapterCollaborateVO.getPlanId(), planChapterCollaborateVO.getChapterId());
            }
        }
        return true;
    }

    @Override
    public CollaborateVO getUsersAndComplete(PlanChapterCollaborateVO planChapterCollaborateVO) {
        SysUser sysUser = SysUtil.getCurrentUserInfo();
        if (sysUser == null || StringUtils.isEmpty(sysUser.getLoginCode())) {
            throw new BusinessException("登录已过期，请重新登录!");
        }
        PlanChapterCollaborate planChapterShare = new PlanChapterCollaborate();
        planChapterShare.setPlanId(planChapterCollaborateVO.getPlanId());
        planChapterShare.setChapterId(planChapterCollaborateVO.getChapterId());
        List<PlanChapterCollaborate> listByCdt = planChapterCollaborateDao.getListByCdt(planChapterShare);
        CollaborateVO collaborateVO = new CollaborateVO();
        if (!CollectionUtils.isEmpty(listByCdt)) {
            PlanChapterCollaborate planChapterCollaborate = listByCdt.get(0);
            List<String> shareMemberList = planChapterCollaborate.getShareMemberList();
            if (!CollectionUtils.isEmpty(shareMemberList)) {
                List<SharedUserVO> userList = new ArrayList<>();
                for (String loginCode : shareMemberList) {
                    UserInfo user = userSvc.getUserInfoByLoginCode(loginCode);
                    if (user != null) {
                        SharedUserVO sharedUserVO = new SharedUserVO();
                        sharedUserVO.setUserName(user.getUserName());
                        sharedUserVO.setLoginCode(user.getLoginCode());
                        sharedUserVO.setIcon(user.getIcon());
                        userList.add(sharedUserVO);
                    }
                }
                collaborateVO.setUserList(userList);

                if (shareMemberList.contains(sysUser.getLoginCode())) {
                    if (planChapterCollaborate.getComplete() != null) {
                        collaborateVO.setComplete(planChapterCollaborate.getComplete());
                    } else {
                        collaborateVO.setComplete(0);
                    }
                    collaborateVO.setButtonSign(1);
                } else {
                    collaborateVO.setButtonSign(0);
                }
            } else {
                collaborateVO.setButtonSign(0);
            }
        }
        PlanDesignInstance planDesignInstance = planDesignInstanceService.getPlanDesignInstance(planChapterCollaborateVO.getPlanId());
        List<SharedUserVO> planSharedList = shareService.findPlanSharedList(planChapterCollaborateVO.getPlanId(), false);
        List<String> loginCodeList = null;
        if (!CollectionUtils.isEmpty(planSharedList)) {
            loginCodeList = planSharedList.stream().filter(sharedUserVO ->
                            Objects.equals(PlanSharePermissionEnum.EDIT_AND_SHARE.getFlag(), sharedUserVO.getPermission())
                                    || Objects.equals(PlanSharePermissionEnum.PUBLISH.getFlag(), sharedUserVO.getPermission()))
                    .map(SharedUserVO::getLoginCode).collect(Collectors.toList());
        }
        if (Objects.equals(planDesignInstance.getCreatorCode(), sysUser.getLoginCode()) || (!CollectionUtils.isEmpty(loginCodeList) && loginCodeList.contains(sysUser.getLoginCode()))) {
            collaborateVO.setHandleUser(1);
        } else {
            collaborateVO.setHandleUser(0);
        }
        return collaborateVO;
    }

    @Override
    public PlanChapterCollaborate getPlanChapterCollaborate(PlanChapterCollaborate planChapterCollaborate) {
        if (planChapterCollaborate == null) {
            throw new BusinessException("参数不能为空!");
        }
        if (planChapterCollaborate.getPlanId() == null) {
            throw new BusinessException("方案信息不能为空!");
        }
        if (planChapterCollaborate.getChapterId() == null) {
            throw new BusinessException("章节信息不能为空!");
        }
        List<PlanChapterCollaborate> collaborateList = planChapterCollaborateDao.getListByCdt(planChapterCollaborate);
        if (!CollectionUtils.isEmpty(collaborateList)) {
            return collaborateList.get(0);
        }
        return null;
    }

    @Override
    public void deletePlanChapterCollaborateUser(PlanChapterCollaborateVO planChapterCollaborateVO) {
        PlanChapterCollaborate planChapterShare = new PlanChapterCollaborate();
        planChapterShare.setPlanId(planChapterCollaborateVO.getPlanId());

        List<PlanChapterCollaborate> listByCdt = planChapterCollaborateDao.getListByCdt(planChapterShare);
        if (!CollectionUtils.isEmpty(listByCdt)) {
            for (PlanChapterCollaborate collaborate : listByCdt) {
                List<String> shareMemberList = collaborate.getShareMemberList();
                if (!CollectionUtils.isEmpty(shareMemberList)) {
                    shareMemberList.removeIf(next -> Objects.equals(next, planChapterCollaborateVO.getLoginCode()));
                    collaborate.setShareMemberList(shareMemberList);
                }
            }
            planChapterCollaborateDao.saveOrUpdateBatch(listByCdt);
        }
    }

    private void pushShareCollaborateNotice(Long planId, Long chapterId, String loginCode) {
        SysUser sysUser = SysUtil.getCurrentUserInfo();
        if (sysUser == null || StringUtils.isEmpty(sysUser.getLoginCode())) {
            throw new BusinessException("登录已过期，请重新登录!");
        }
        UserInfo userInfo = userSvc.getUserInfoByLoginCode(sysUser.getLoginCode());

        PlanDesignInstance planDesignInstance = planDesignInstanceService.getPlanDesignInstance(planId);
        ChapterInstance planChapterInstance = planChapterInstanceService.getPlanChapterInstance(chapterId);

        EamNotice notice = new EamNotice();
        notice.setId(ESUtil.getUUID());
        notice.setDomainId(1L);
        notice.setType(NoticeConstant.NOTICE_TYPE_MSG);
        notice.setClassify(NoticeConstant.NOTICE_CLASSIFY_SYSTEM);
        notice.setRead(0);

        notice.setContent(String.format(NoticeConstant.PLAN_CHAPTER_SHARE_COLLABORATE, userInfo.getUserName(), planDesignInstance.getName(), planChapterInstance.getName()));
        notice.setUserName(loginCode);

        List<EamNoticeKeyword> keywords = new ArrayList<>();
        Map<String, Object> planParams = new ConcurrentHashMap<>();
        planParams.put(NoticeConstant.SOURCE_TYPE, 0);
        planParams.put(NoticeConstant.PLAN_ID, String.valueOf(planId));
        keywords.add(new EamNoticeKeyword(planDesignInstance.getName(), planParams));
        Map<String, Object> chapterParams = new ConcurrentHashMap<>();
        chapterParams.put(NoticeConstant.SOURCE_TYPE, 0);
        chapterParams.put(NoticeConstant.PLAN_ID, String.valueOf(planId));
        chapterParams.put(NoticeConstant.CHAPTER_ID, String.valueOf(planChapterInstance.getId()));
        keywords.add(new EamNoticeKeyword(planChapterInstance.getName(), chapterParams));
        notice.setKeywords(keywords);

        notice.setTag(NoticeConstant.TAG_PLAN);
        notice.setCustomer(String.valueOf(planChapterInstance.getId()));
        notice.setCustomer1(String.valueOf(userInfo.getId()));
        notice.setCustomer2(String.valueOf(planDesignInstance.getId()));
        notice.setCustomer3(userInfo.getUserName());
        notice.setIsDeleted(0);
        notice.setMsgType(NoticeConstant.MSG_TYPE_SHARE_COLLABORATE);

        List<EamNotice> notices = new ArrayList<>();
        notices.add(notice);
        eamNoticeService.batchSaveNotice(notices);
    }

    private void pushCompleteCollaborateNotice(Long planId, Long chapterId) {
        SysUser sysUser = SysUtil.getCurrentUserInfo();
        if (sysUser == null || StringUtils.isEmpty(sysUser.getLoginCode())) {
            throw new BusinessException("登录已过期，请重新登录!");
        }
        UserInfo userInfo = userSvc.getUserInfoByLoginCode(sysUser.getLoginCode());

        PlanDesignInstance planDesignInstance = planDesignInstanceService.getPlanDesignInstance(planId);
        ChapterInstance planChapterInstance = planChapterInstanceService.getPlanChapterInstance(chapterId);

        List<EamNotice> notices = new ArrayList<>();
        List<SharedUserVO> planSharedList = shareService.findPlanSharedList(planDesignInstance.getId(), true);
        if (CollectionUtils.isEmpty(planSharedList)) {
            planSharedList = new ArrayList<>();
        }
        // 新增方案的拥有者，并发送消息
        SharedUserVO sharedUserVO = new SharedUserVO();
        sharedUserVO.setPermission(PlanSharePermissionEnum.EDIT_AND_SHARE.getFlag());
        sharedUserVO.setLoginCode(planDesignInstance.getCreatorCode());
        planSharedList.add(sharedUserVO);
        for (SharedUserVO sharedUser : planSharedList) {
            if ((!Objects.equals(sharedUser.getPermission(), PlanSharePermissionEnum.EDIT_AND_SHARE.getFlag())
                    && !Objects.equals(sharedUser.getPermission(), PlanSharePermissionEnum.PUBLISH.getFlag()))
                    || Objects.equals(sharedUser.getLoginCode(), sysUser.getLoginCode())) {
                continue;
            }
            EamNotice notice = new EamNotice();
            notice.setId(ESUtil.getUUID());
            notice.setDomainId(1L);
            notice.setType(NoticeConstant.NOTICE_TYPE_MSG);
            notice.setClassify(NoticeConstant.NOTICE_CLASSIFY_SYSTEM);
            notice.setRead(0);

            notice.setContent(String.format(NoticeConstant.PLAN_CHAPTER_COMPLETE_COLLABORATE, userInfo.getUserName(), planDesignInstance.getName(), planChapterInstance.getName()));
            notice.setUserName(sharedUser.getLoginCode());

            List<EamNoticeKeyword> keywords = new ArrayList<>();
            Map<String, Object> planParams = new ConcurrentHashMap<>();
            planParams.put(NoticeConstant.SOURCE_TYPE, 0);
            planParams.put(NoticeConstant.PLAN_ID, String.valueOf(planId));
            keywords.add(new EamNoticeKeyword(planDesignInstance.getName(), planParams));
            Map<String, Object> chapterParams = new ConcurrentHashMap<>();
            chapterParams.put(NoticeConstant.SOURCE_TYPE, 0);
            chapterParams.put(NoticeConstant.PLAN_ID, String.valueOf(planId));
            chapterParams.put(NoticeConstant.CHAPTER_ID, String.valueOf(planChapterInstance.getId()));
            keywords.add(new EamNoticeKeyword(planChapterInstance.getName(), chapterParams));
            notice.setKeywords(keywords);

            notice.setTag(NoticeConstant.TAG_PLAN);
            notice.setCustomer(String.valueOf(planChapterInstance.getId()));
            notice.setCustomer1(String.valueOf(userInfo.getId()));
            notice.setCustomer2(String.valueOf(planDesignInstance.getId()));
            notice.setCustomer3(userInfo.getUserName());
            notice.setIsDeleted(0);
            notice.setMsgType(NoticeConstant.MSG_TYPE_COMPLETE_COLLABORATE);
            notices.add(notice);
        }
        eamNoticeService.batchSaveNotice(notices);
    }

    @Override
    public Map<Long, PlanChapterCollaborate> getByPlanId(Long planId) {
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        query.must(QueryBuilders.termQuery("planId", planId));
        List<PlanChapterCollaborate> result = planChapterCollaborateDao.getListByQuery(query);
        if(CollectionUtils.isEmpty(result)){
            return new HashMap<>();
        }
        return result.stream().collect(Collectors.toMap(PlanChapterCollaborate::getChapterId, e -> e, (k1, k2) -> k2));
    }
}
